// src/mock/accountPermissionManagementMock.ts

import Mock from 'mockjs';
// import type { MockjsRequestOptions } from 'mockjs'; // 已不再使用，注释掉

// 兼容JSON和FormData的body解析
function parseBody(options: { body?: unknown }): Record<string, unknown> {
  if (!options.body) return {};
  if (typeof options.body === 'string') {
    try {
      return JSON.parse(options.body);
    } catch {
      return {};
    }
  }
  if (typeof FormData !== 'undefined' && options.body instanceof FormData) {
    const obj: Record<string, unknown> = {};
    for (const [key, value] of options.body.entries()) {
      obj[key] = value;
    }
    return obj;
  }
  return options.body as Record<string, unknown>;
}

// 角色相关mock - 使用OpenAPI文档中的示例数据
let roleList = [
  {
    id: 1,
    roleName: '超级管理员',
    type: '系统角色',
    memberCount: 2,
    permissionList: JSON.stringify(['0202', '0402', '0501', '0502', '0503', '0504', '0601', '0602', '0603', '0604'])
  },
  {
    id: 2,
    roleName: '管理员',
    type: '系统角色',
    memberCount: 0,
    permissionList: JSON.stringify(['0202', '0402', '0501', '0502', '0503', '0504'])
  },
  {
    id: 3,
    roleName: '默认角色',
    type: '系统角色',
    memberCount: 0,
    permissionList: JSON.stringify(['0202', '0402'])
  },
  {
    id: 4,
    roleName: '客服经理',
    type: '系统角色',
    memberCount: 0,
    permissionList: JSON.stringify(['0202', '0402', '0501'])
  },
  {
    id: 5,
    roleName: '主办会计',
    type: '系统角色',
    memberCount: 0,
    permissionList: JSON.stringify(['0202'])
  },
  {
    id: 6,
    roleName: '出纳',
    type: '系统角色',
    memberCount: 0,
    permissionList: JSON.stringify([])
  },
  {
    id: 7,
    roleName: '销售经理',
    type: '系统角色',
    memberCount: 0,
    permissionList: JSON.stringify(['0501', '0502'])
  },
  {
    id: 8,
    roleName: '空角色',
    type: '自定义角色',
    memberCount: 0,
    permissionList: JSON.stringify([])
  },
  {
    id: 9,
    roleName: '自定义角色',
    type: '自定义角色',
    memberCount: 0,
    permissionList: JSON.stringify(['0202', '0402', '0501', '0601'])
  }
];

Mock.mock('/api/role/getRoleList', 'post', () => ({
  code: '100',
  message: '操作成功',
  data: roleList
}));

Mock.mock('/api/role/addRole', 'post', (options) => {
  const body = parseBody(options);
  const newId = Date.now();
  roleList.push({
    id: newId,
    roleName: String((body as Record<string, unknown>).roleName),
    type: '自定义角色',
    memberCount: 0,
    permissionList: String((body as Record<string, unknown>).permissionList || '[]')
  });
  return { code: '100', message: '操作成功', data: null };
});

Mock.mock('/api/role/editRole', 'post', (options) => {
  const body = parseBody(options);
  const idx = roleList.findIndex(r => String(r.id) === String((body as Record<string, unknown>).id));
  if (idx > -1) {
    roleList[idx] = {
      ...roleList[idx],
      roleName: String((body as Record<string, unknown>).roleName),
      permissionList: String((body as Record<string, unknown>).permissionList || '[]')
    };
  }
  return { code: '100', message: '操作成功', data: null };
});

Mock.mock('/api/role/deleteRole', 'post', (options) => {
  const body = parseBody(options);
  roleList = roleList.filter(r => String(r.id) !== String((body as Record<string, unknown>).id));
  return { code: '100', message: '操作成功', data: null };
});

Mock.mock('/api/role/getRoleDropdownList', 'post', () => ({
  code: '100',
  message: '操作成功',
  data: roleList.map(r => ({
    id: r.id,
    roleName: r.roleName,
    type: r.type,
    memberCount: 0
  }))
}));

// 新增：角色详情接口，返回 permissionList
Mock.mock('/api/role/viewRole', 'post', (options) => {
  const body = parseBody(options);
  const role = roleList.find(r => String(r.id) === String((body as Record<string, unknown>).id));
  if (!role) {
    return {
      code: '404',
      message: '未找到角色',
      data: null
    };
  }
  return {
    code: '100',
    message: '操作成功',
    data: {
      id: role.id,
      roleName: role.roleName,
      type: role.type,
      permissionCode: JSON.parse(role.permissionList || '[]')
    }
  };
});

// 角色ID到角色名映射
const roleMap: Record<string, string> = {
  '1': '超级管理员',
  '2': '管理员',
  '3': '默认角色',
  '4': '客服经理',
  '5': '主办会计',
  '6': '出纳',
  '7': '销售经理',
  '8': '空角色',
  '9': '自定义角色'
};

// 账号相关mock（可变内存数据）- 使用OpenAPI文档中的示例数据
let userList = [
  {
    id: 4,
    userType: '后台管理',
    mobile: '13000000001',
    userName: '2',
    nickname: '2',
    avatar: '2',
    status: '启用',
    createdAt: '2025-06-18 10:40:26',
    updatedAt: null,
    deletedAt: null,
    roleList: [
      {
        id: 3,
        roleName: '默认角色',
        type: '系统角色'
      }
    ]
  },
  {
    id: 2,
    userType: '后台管理',
    mobile: '13857185554',
    userName: '超级管理员',
    nickname: '超级管理员',
    avatar: null,
    status: '启用',
    createdAt: '2025-06-16 20:40:26',
    updatedAt: null,
    deletedAt: null,
    roleList: [
      {
        id: 1,
        roleName: '超级管理员',
        type: '系统角色'
      }
    ]
  },
  {
    id: 1,
    userType: '后台管理',
    mobile: '13588816882',
    userName: '超级管理员',
    nickname: '超级管理员',
    avatar: null,
    status: '启用',
    createdAt: '2025-06-15 08:30:00',
    updatedAt: null,
    deletedAt: null,
    roleList: [
      {
        id: 1,
        roleName: '超级管理员',
        type: '系统角色'
      }
    ]
  }
];

Mock.mock('/api/user/getAdminListByPage', 'post', (options) => {
  // 支持分页和搜索
  const body = parseBody(options);
  let list = userList;

  if ((body as Record<string, unknown>).roleID) {
    list = list.filter(u => u.roleList.some(r => String(r.id) === String((body as Record<string, unknown>).roleID)));
  }
  if ((body as Record<string, unknown>).keyword) {
    list = list.filter(u => u.userName.includes(String((body as Record<string, unknown>).keyword)) || u.mobile.includes(String((body as Record<string, unknown>).keyword)));
  }

  // 新增：排序逻辑
  if ((body as Record<string, unknown>).orderBy) {
    try {
      const orderObj = typeof body.orderBy === 'string' ? JSON.parse(body.orderBy as string) : body.orderBy;
      if (orderObj.field && orderObj.order) {
        list = list.slice().sort((a, b) => {
          const aVal = (a as any)[orderObj.field];
          const bVal = (b as any)[orderObj.field];
          // 针对 createdAt 字段用时间戳比较
          if (orderObj.field === 'createdAt') {
            const aTime = new Date(aVal).getTime();
            const bTime = new Date(bVal).getTime();
            if (aTime === bTime) return 0;
            if (orderObj.order === 'ascend') {
              return aTime - bTime;
            } else {
              return bTime - aTime;
            }
          }
          // 其它字段按原逻辑
          if (aVal === bVal) return 0;
          if (orderObj.order === 'ascend') {
            return aVal > bVal ? 1 : -1;
          } else {
            return aVal < bVal ? 1 : -1;
          }
        });
      }
    } catch (e) {
      // 忽略排序错误
    }
  }

  const page = Number((body as Record<string, unknown>).page) || 1;
  const pageSize = Number((body as Record<string, unknown>).pageSize) || 10;
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  const total = list.length;
  const totalPage = Math.ceil(total / pageSize);

  return {
    code: '100',
    message: '操作成功',
    data: {
      pageData: {
        total,
        pageSize,
        totalPage,
        page,
        startIdx: start,
        endIdx: Math.min(end, total),
        offset: total,
        list: list.slice(start, end)
      }
    }
  };
});

Mock.mock('/api/user/addAdminUser', 'post', (options) => {
  const body = parseBody(options);
  const newId = Date.now();
  const roleID = String((body as Record<string, unknown>).roleID);
  const roleName = roleMap[roleID] || '';
  const role = roleID ? [{ id: Number(roleID), roleName, type: Number(roleID) <= 7 ? '系统角色' : '自定义角色' }] : [];

  userList.push({
    id: newId,
    userType: '后台管理',
    mobile: String((body as Record<string, unknown>).mobile),
    userName: String((body as Record<string, unknown>).userName),
    nickname: String((body as Record<string, unknown>).userName),
    avatar: String((body as Record<string, unknown>).avatar || ''),
    status: '启用',
    createdAt: new Date().toISOString().slice(0, 19).replace('T', ' '),
    updatedAt: null,
    deletedAt: null,
    roleList: role
  });

  return { code: '100', message: '操作成功', data: null };
});

Mock.mock('/api/user/editAdminUser', 'post', (options) => {
  const body = parseBody(options);
  const idx = userList.findIndex(u => String(u.id) === String((body as Record<string, unknown>).id));

  if (idx > -1) {
    const roleID = String((body as Record<string, unknown>).roleID);
    const roleName = roleMap[roleID] || '';
    const role = roleID ? [{ id: Number(roleID), roleName, type: Number(roleID) <= 7 ? '系统角色' : '自定义角色' }] : userList[idx].roleList;

    // 检查是否要修改手机号（需要验证码）
    let newMobile = userList[idx].mobile;
    if ((body as Record<string, unknown>).oldMobile && 
        (body as Record<string, unknown>).oldMobileCode && 
        (body as Record<string, unknown>).newMobile && 
        (body as Record<string, unknown>).newMobileCode) {
      // 验证原手机号和验证码
      if (String((body as Record<string, unknown>).oldMobile) === userList[idx].mobile) {
        newMobile = String((body as Record<string, unknown>).newMobile);
      }
    }

    userList[idx] = {
      ...userList[idx],
      userName: String((body as Record<string, unknown>).userName),
      nickname: String((body as Record<string, unknown>).userName),
      mobile: newMobile,
      roleList: role,
      avatar: String((body as Record<string, unknown>).avatar || userList[idx].avatar)
    };
  }

  return { code: '100', message: '操作成功', data: null };
});

Mock.mock('/api/user/deleteUser', 'post', (options) => {
  const body = parseBody(options);
  userList = userList.filter(u => String(u.id) !== String((body as Record<string, unknown>).id));
  return { code: '100', message: '操作成功', data: null };
});

Mock.mock('/api/user/changeUserStatus', 'post', (options) => {
  const body = parseBody(options);
  const idx = userList.findIndex(u => String(u.id) === String((body as Record<string, unknown>).id));

  if (idx > -1) {
    userList[idx].status = String((body as Record<string, unknown>).status);
  }

  return { code: '100', message: '操作成功', data: null };
});

Mock.mock('/api/user/viewAdminUser', 'post', (options) => {
  const body = parseBody(options);
  const user = userList.find(u => String(u.id) === String((body as Record<string, unknown>).id));

  return {
    code: '100',
    message: '操作成功',
    data: user || null
  };
});

Mock.mock('/api/user/getUserDropdownList', 'post', () => ({
  code: '100',
  message: '操作成功',
  data: userList.map(u => ({
    id: u.id,
    userType: null,
    mobile: u.mobile,
    userName: u.userName,
    nickname: null,
    avatar: null,
    status: null,
    createdAt: null,
    updatedAt: null,
    deletedAt: null
  }))
}));

// 文件上传mock接口 - 按照接口文档格式
Mock.mock('/api/kf/upload', 'post', {
  code: '100',
  message: '操作成功',
  data: {
    file: {
      uid: 'mock-file-' + Date.now(),
      filename: 'mock-avatar.jpg',
      extname: '.jpg',
      url: 'https://picsum.photos/100/100?random=' + Date.now()
    }
  }
});
